package com.sky.service.impl;

import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.core.enums.SQLExecuteStrategyEnum;
import com.easy.query.core.expression.builder.core.NotNullOrEmptyValueFilter;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.entity.proxy.EmployeeProxy;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EasyEntityQuery easyEntityQuery;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    /*
    @Deprecated
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // md5 处理
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
*/
    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login_easyquery(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
//        Employee employee = employeeMapper.getByUsername(username);
//        select * from employee where username = #{username}
        final Employee employee = easyEntityQuery.queryable(Employee.class)
                .where(emp -> {
                    emp.username().eq(username);
                })
                .firstNotNull(()-> new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND));

        log.info("easyquery 查询结果：{}", employee);
//        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
//        if (employee == null) {
//            //账号不存在
//            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
//        }

        //密码比对
        // md5 处理
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {


        Long currentId = BaseContext.getCurrentId();

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置账号状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置创建时间
        employee.setCreateTime(LocalDateTime.now());
        //设置更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //设置创建人
        employee.setCreateUser(BaseContext.getCurrentId());
        //设置更新人
        employee.setUpdateUser(BaseContext.getCurrentId());


//        insert into employee (name, username, password, phone, sex, id_number, create_time, update_time, create_user, update_user,status) " +
//        "value " +
//        "(#{name}, #{username}, #{password}, #{phone}, #{sex}, #{idNumber}, now(), now(), #{createUser}, #{updateUser}, #{status})")
//        employeeMapper.insert(employee);
//        log.info("插入前employee id：{}", employee.getId());

        final List<Employee> employeeList = new ArrayList<>();
        employeeList.add(employee);

        for (int i = 0; i < 50; i++) {
            var tmpEmp = new Employee();
            BeanUtils.copyProperties(employee, tmpEmp);
            tmpEmp.setUsername(tmpEmp.getUsername() + i);

            employeeList.add(tmpEmp);
        }


        final long executeRows = easyEntityQuery.insertable(employeeList)
//                .insert(employee2)
//                .insert(employee3)
//                .insert(employee4)
//                .setSQLStrategy(SQLExecuteStrategyEnum.ALL_COLUMNS) //Easy-Query作者是这个不强制
//                .batch()
                .executeRows(true);
        log.info("executeRows = {}", executeRows);
//        log.info("插入结束后employee id：{}", employee.getId());

    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult<Employee> pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        // select * from employee whereif name like '%appl%l limit 0,10
        // 实际查询
/*  还有这两种写法
final EasyPageResult<Employee> pageResult = easyEntityQuery.queryable(Employee.class)
                .where(emp ->
                        emp.name().like(StringUtils.hasLength(employeePageQueryDTO.getName()),employeePageQueryDTO.getName()))

                .toPageResult(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());



        final EasyPageResult<Employee> pageResult1 = easyEntityQuery.queryable(Employee.class)
                .where(StringUtils.hasLength(employeePageQueryDTO.getName()),emp ->
                        emp.name().like(employeePageQueryDTO.getName()))

                .toPageResult(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
*/

        final var pageResult = easyEntityQuery.queryable(Employee.class)
                // 过滤掉空值，动态查询的核心，
                // 参见 http://www.easy-query.com/easy-query-doc/guide/query/dynamic-where.html
                .filterConfigure(NotNullOrEmptyValueFilter.DEFAULT)
                .where(emp -> emp.name().like(employeePageQueryDTO.getName()))
                .toPageResult(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());



        final List<Employee> employeeList = pageResult.getData();
        final long total = pageResult.getTotal();

        return PageResult.<Employee>builder()
                .total(total)
                .records(employeeList)
                .build();
    }


}
